package cn.fl.project.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjCstRepayAbiQueryCondition;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjCstRepayAbiService;
import cn.fl.project.vo.PrjCstRepayAbiVO;
import cn.fl.system.constant.SysLogConstant;
import fl.customer.facade.customer.constant.CustomerConstant;

/**
 * @Description: 客户还款能力调查表 控制层
 */
@Controller
@RequestMapping("/project/prjcstrepayabi")
public class PrjCstRepayAbiController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(PrjCstRepayAbiController.class);


	/**
	 * PrjCstRepayAbi 服务层BEAN
	 */
	@Autowired
	private IPrjCstRepayAbiService prjCstRepayAbiService;
	@Autowired
	private IPrjBscInfoService prjBscInfoService;
	

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		String prjId = request.getParameter("prjId");
		String detailFlag = request.getParameter("detailFlag");
		String cstRlCd = request.getParameter("cstRlCd");//客户关系
		Long cstId =null;
		String cstType = "";
		if(StringUtils.isNotBlank(prjId)){
			CstBscInfoVO cst = 	this.prjBscInfoService.getCstTypByPrjId(Long.valueOf(prjId));
			if(null!=cst){
				cstId = cst.getId();
				cstType = cst.getCstTypCd();
			}
		}
		PrjCstRepayAbiVO abi  = null;
		
		if(StringUtils.isNotBlank(prjId)&&null!=cstId){
			abi = this.prjCstRepayAbiService.getPrjCstRepayAbiByPrjIdAndCstId(Long.valueOf(prjId),cstId,cstRlCd);//通过项目和客户id查询客户还款能力
		}
		List<KeyValueVO> keyList =  this.prjBscInfoService.getPayStlCdList();
		ModelAndView view = new ModelAndView("project/prjcstrepayabi/prjcstrepayabiAdd");
		view.addObject("prjId", prjId);
		view.addObject("cstId", cstId);
		view.addObject("abi", abi);
		view.addObject("cstType", cstType);
		view.addObject("keyList", keyList);
		view.addObject("detailFlag", detailFlag);
		view.addObject("cstRlCd", cstRlCd);
		BaseLogUtils.info(logger, "toListPage", "跳转到添加页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("project/prjCstRepayAbi/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		PrjCstRepayAbiQueryCondition qc = new PrjCstRepayAbiQueryCondition();
		if (StringUtils.isNotEmpty(searchName)) {
			//TODO SOMTHING
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager =  this.prjCstRepayAbiService.searchListPage(page);
		List<PrjCstRepayAbiVO> list = (List<PrjCstRepayAbiVO>) pager.getResultList();
		ListPageVO<PrjCstRepayAbiVO> listPage = new ListPageVO<PrjCstRepayAbiVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.prjCstRepayAbiService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			PrjCstRepayAbiVO vo = this.prjCstRepayAbiService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String abiId = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		PrjCstRepayAbiVO entity = null;
		Long id = null;
		try {
			PrjCstRepayAbiVO prjCstRepayAbiVO = getPrjCstRepayAbiParam(request);
			if(StringUtils.isNotBlank(abiId)){
				//修改客户调查报告
				prjCstRepayAbiVO.setId(Long.valueOf(abiId));
				this.prjCstRepayAbiService.modify(prjCstRepayAbiVO);
				result.setSuccess(BaseConstant.IS_YESNO_YES);
				result.setInfo(SysLogConstant.LOG_CMM_OPERATE_SUCC);
				id=Long.valueOf(abiId);
			}else{
				//获取页面参数
				prjCstRepayAbiVO.setCrtTm(new Date());
				prjCstRepayAbiVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				prjCstRepayAbiVO.setIsDel(BaseConstant.IS_YESNO_NO);
				 id = this.prjCstRepayAbiService.add(prjCstRepayAbiVO);
			}
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	private PrjCstRepayAbiVO getPrjCstRepayAbiParam(HttpServletRequest request) {
		PrjCstRepayAbiVO abi = new PrjCstRepayAbiVO();
		String prjId = request.getParameter("prjId");
		String cstId = request.getParameter("cstId");
		String ownCarNum = request.getParameter("ownCarNum");
		String mgrCarNum = request.getParameter("mgrCarNum");
		String cstNum = request.getParameter("cstNum");
		String year = request.getParameter("year");
		String payStlCd = request.getParameter("payStlCd");
		String hsePptLandSts = request.getParameter("hsePptLandSts");
		String assScl = request.getParameter("assScl");
		String debt = request.getParameter("debt");
		String netAss = request.getParameter("netAss");
		String liqAss = request.getParameter("liqAss");
		String fixAss = request.getParameter("fixAss");
		String assDebtRate = request.getParameter("assDebtRate");
		String mainBusiIncm = request.getParameter("mainBusiIncm");
		String netPrft = request.getParameter("netPrft");
		String lstYearPrft = request.getParameter("lstYearPrft");
		String payFrqnc = request.getParameter("payFrqnc");
		String contatAbltRato = request.getParameter("contatAbltRato");
		String extMbDesc = request.getParameter("extMbDesc");
		String cstRlCd = request.getParameter("cstRlCd");//客户关系
		String isCrimRecd = request.getParameter("isCrimRecd");//是否有犯罪记录或诉讼案件
		String isFinaInstAss = request.getParameter("isFinaInstAss");//是否曾经被金融机构执行资产
		String apyCrdtCd = request.getParameter("apyCrdtCd");//企业我司信用记录
		String corpReprCrdtCd = request.getParameter("corpReprCrdtCd");//法人代表我司信用记录
		String guarAbiDesc = request.getParameter("guarAbiDesc");//担保能力说明
		String apyRelDesc = request.getParameter("apyRelDesc");//与融资租赁业务申请人关系说明
		
		if(StringUtils.isNotBlank(prjId)){
			abi.setPrjId(Long.valueOf(prjId));
		}
		if(StringUtils.isNotBlank(cstId)){
			abi.setCstId(Long.valueOf(cstId));
		}
			abi.setCstRlCd(cstRlCd);
			if(StringUtils.isNotBlank(isCrimRecd)){
				abi.setIsCrimRecd(Integer.valueOf(isCrimRecd));
			}
			if(StringUtils.isNotBlank(isFinaInstAss)){
				abi.setIsFinaInstAss(Integer.valueOf(isFinaInstAss));
			}
			abi.setApyCrdtCd(apyCrdtCd);
			abi.setCorpReprCrdtCd(corpReprCrdtCd);
			abi.setGuarAbiDesc(guarAbiDesc);
			abi.setApyRelDesc(apyRelDesc);
			abi.setOwnCarNum(ownCarNum);
			abi.setMgrCarNum(mgrCarNum);
			abi.setCstNum(cstNum);
			abi.setYear(year);
			abi.setPayStlCd(payStlCd);
			abi.setHsePptLandSts(hsePptLandSts);
			abi.setAssScl(assScl);
			abi.setDebt(debt);
			abi.setNetAss(netAss);
			abi.setLiqAss(liqAss);
			abi.setFixAss(fixAss);	
			abi.setAssDebtRate(assDebtRate);
			abi.setMainBusiIncm(mainBusiIncm);
			abi.setNetPrft(netPrft);
			abi.setLstYearPrft(lstYearPrft);
			abi.setPayFrqnc(payFrqnc);
			abi.setContatAbltRato(contatAbltRato);
			abi.setExtMbDesc(extMbDesc);
		return abi;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		PrjCstRepayAbiVO entity = null;
		try {
			entity = new PrjCstRepayAbiVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.prjCstRepayAbiService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 到担保人能力页面
	 */
	@RequestMapping(value = "/toGuarAddPage.do", method = { RequestMethod.GET})
	public ModelAndView toGuarAddPage(HttpServletRequest request, HttpServletResponse response) {
		String prjId = request.getParameter("prjId");
		String detailFlag = request.getParameter("detailFlag");
		String cstRlCd = request.getParameter("cstRlCd");//客户关系
		String cstId = request.getParameter("cstId");//客户ID
		String cstType = request.getParameter("cstTypCd");//客户类型
		PrjCstRepayAbiVO abi  = null;
		String pageUrl = "";
		if(StringUtils.isNotBlank(prjId)&&null!=cstId){
			abi = this.prjCstRepayAbiService.getPrjCstRepayAbiByPrjIdAndCstId(Long.valueOf(prjId),Long.valueOf(cstId),cstRlCd);//通过项目和客户id查询客户还款能力
		}
		if(StringUtils.isNotBlank(cstType)&&cstType.equals(CustomerConstant.CST_TYP_CD_NP)){
			//自然人
			pageUrl = "project/prjcstrepayabi/prjguarnprepayabiAdd";
		}
		if(StringUtils.isNotBlank(cstType)&&cstType.equals(CustomerConstant.CST_TYP_CD_CORP)){
			//法人
			pageUrl = "project/prjcstrepayabi/prjguarcorprepayabiAdd";
		}
		List<KeyValueVO> keyList = this.prjBscInfoService.getPrjApyCrdtList();//信用记录
		List<KeyValueVO> YesNoList = this.prjBscInfoService.getYesNoList();//是否列表
		ModelAndView view = new ModelAndView(pageUrl);
		view.addObject("prjId", prjId);
		view.addObject("cstId", cstId);
		view.addObject("abi", abi);
		view.addObject("cstType", cstType);
		view.addObject("keyList", keyList);
		view.addObject("detailFlag", detailFlag);
		view.addObject("cstRlCd", cstRlCd);
		view.addObject("YesNoList", YesNoList);
		BaseLogUtils.info(logger, "toListPage", "跳转到添加页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}
}

